/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable max-len */
/* 单号使用统计 */
import React, { Component } from 'react';
import StandardTable from '@/components/StandardTable';
import ExpressModal from '@/components/ExpressModal';
import { Button, Row, Col, message } from 'antd';
import { connect } from 'dva';
import moment from 'moment/moment';
import { debounce } from 'lodash';
import DownLoadModal from '../DownLoadModal';
import Details from './Details';
import SearchBar from '../SearchBar';
import pageConfig from '../orderPageConfig';

@connect(({ loading, orderRecord }) => ({
  orderRecord,
  getStatisticsList: loading.effects['orderRecord/getStatisticsList'],
  wsLoading: loading.effects['orderRecord/getWsStatisticsList'],
  yzLoading: loading.effects['orderRecord/getYZStatisticsList'],
}))
export default class OrderStatistics extends Component {
  // eslint-disable-next-line react/sort-comp
  handleTableChange = debounce(
    pagination => {
      const { dispatch } = this.props;
      const { formValues } = this.formRef.state;

      this.setState({ page: pagination.current });
      dispatch({
        type: this.actionTypes.statistics,
        payload: {
          ...formValues,
          page: pagination.current,
        },
      });
    },
    500,
    {
      leading: true,
      trailing: false,
    },
  );

  constructor(props) {
    super(props);
    const { sourceType } = props;
    this.pageConfig = pageConfig.call(this, sourceType); // sourceType 区分业务员（operator），微商（derivative），驿站（yz）
    this.state = {
      showDetail: false,
      expressInfo: null,
      type: 'statistics',
    };
    const { orderStatisticsColums, actionTypes } = this.pageConfig;
    this.tableColum = orderStatisticsColums;
    this.actionTypes = actionTypes;
    this.formRef = React.createRef();
  }

  componentDidMount() {
    this.getList();
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.activeKey !== this.props.activeKey && nextProps.activeKey == 'statistics') {
      this.formRef.props.form.resetFields(); // 重置查询值
      this.setState({ showDetail: false });
      this.getList();
    }
  }

  getList = () => {
    const { dispatch, sourceType } = this.props;
    const { cmId, brand, keyword, data_end, data_start, ws_id } = this.formRef.state;
    let payload = {
      site_id: cmId,
      brand,
      keyword,
      start_time: moment(data_start).format('YYYY-MM-DD'),
      end_time: moment(data_end).format('YYYY-MM-DD'),
      page: 1,
    };

    if (sourceType === 'derivative') {
      payload = {
        ws_id,
        start_time: moment(data_start).format('YYYY-MM-DD'),
        end_time: moment(data_end).format('YYYY-MM-DD'),
        page: 1,
        is_new: 1,
      };
    }
    dispatch({
      type: this.actionTypes.statistics,
      payload,
    });
  };

  // 展示物流
  showExpressModal = data => {
    const { brand, brand_cn, waybill_no } = data;
    this.setState({
      expressInfo: {
        brand,
        waybill_no,
        brand_name: brand_cn,
        visible: false,
      },
    });
  };

  toggleDetail = (bool, record = {}, type = '') => {
    this.setState({
      showDetail: bool,
      record,
      type,
    });
  };

  // 添加下载任务
  addDownLoad = () => {
    const { dispatch, sourceType } = this.props;
    const { page } = this.state;
    const { formValues } = this.formRef.state;
    const { start_time, end_time } = formValues;

    const diffDays = moment(end_time).diff(moment(start_time), 'day');
    if (diffDays >= 30) {
      message.error('只支持下载时间跨度一个月的记录！');
      return;
    }
    const payload = {
      ...formValues,
      page,
      type: 2,
    };
    const { statisticsAddDownLoad } = this.actionTypes;
    if (sourceType == 'derivative') {
      payload.type = 5;
    }
    if (sourceType == 'yz') {
      payload.type = 7;
    }
    dispatch({
      type: statisticsAddDownLoad,
      payload,
    });
  };

  // 查看下载任务
  checkDownLoadTask = () => {
    const { dispatch, sourceType } = this.props;
    const payload = {
      page: 1,
    };
    const { statisticsGetDownLoadList } = this.actionTypes;
    if (sourceType == 'derivative') {
      payload.type = 5;
    }
    if (sourceType == 'yz') {
      payload.type = 7;
    }
    dispatch({
      type: statisticsGetDownLoadList,
      payload,
    });
    this.toggleModal(true);
  };

  toggleModal = open => {
    this.setState({ visible: open });
  };

  render() {
    const { expressInfo, showDetail, visible, record, type } = this.state;
    const {
      getStatisticsList,
      orderRecord: { statisticsList },
      sourceType,
      wsLoading,
      yzLoading,
    } = this.props;
    return (
      <div>
        <SearchBar
          sourceType={sourceType}
          actionTypes={this.actionTypes}
          wrappedComponentRef={form => {
            this.formRef = form;
          }}
          type={type}
          show
        />
        {showDetail ? (
          <Details
            goBack={() => this.toggleDetail(false, {}, 'checkDetail')}
            formState={this.formRef.state}
            record={record}
            sourceType={sourceType}
            actionTypes={this.actionTypes}
          />
        ) : (
          <div>
            <Row type="flex" gutter={[8]} style={{ marginBottom: 20 }}>
              <Col>
                <Button type="primary" onClick={this.addDownLoad}>
                  添加下载任务
                </Button>
              </Col>
              <Col>
                <Button type="primary" onClick={this.checkDownLoadTask}>
                  查看下载任务
                </Button>
              </Col>
            </Row>
            <StandardTable
              // eslint-disable-next-line no-shadow
              rowKey={record => record.user_id || record.data.retail_id}
              columns={this.tableColum}
              data={statisticsList}
              loading={getStatisticsList || wsLoading || yzLoading}
              onChange={this.handleTableChange}
              scroll={{ x: 800 }}
            />
            <ExpressModal
              cleanData={() => {
                this.setState({
                  expressInfo: null,
                });
              }}
              data={expressInfo}
            />
            <DownLoadModal
              sourceType={sourceType}
              visible={visible}
              hideModal={() => this.toggleModal(false)}
              title="下载任务"
              type="statistics"
            />
          </div>
        )}
      </div>
    );
  }
}
